<template>
	<view class="order-page">
		<!-- 顶部导航 -->
		<view class="header" :style="{ 'paddingTop': statusBarHeight + 'px' }">
			<text class="title">我的订单</text>
			<view class="filter">
				<picker @change="filterChange" :range="filterOptions.map(v => v.msg)">
					<view class="filter-btn">
						<text>{{ filterOptions.find(v => v.code === currentFilter).msg }}</text>
						<uni-icons type="down" size="15"></uni-icons>
					</view>
				</picker>
			</view>
		</view>
		<view class="fill"></view>

		<!-- 订单列表 -->
		<view class="order-list">
			
			<Page 
				ref="pageRef"
				:page-function="getAllMyOrderList" 
				v-model:dataList="orderList" 
				v-model:page="page"
				@refresh=""
			>
				<!-- 订单卡片 -->
				<view 
					v-for="(order, index) in orderList" 
					:key="index" 
					class="order-card"
				>
					<!-- 用户信息 -->
					<view class="user-info">
						<image 
							class="avatar" 
							:src="getUserAvatarOrDefault(order.avatar)" 
							alt="用户头像"
							mode="aspectFill"
						></image>
						<text class="username">{{ order.username }}</text>
						<view class="tag-container">
							<view class="view-more" @tap="gotoInfoPage(order)">
								查看详情
							</view>
							<view class="status-tag">
								{{ getTypeNameByCode(order.status) }}
							</view>
						</view>
					</view>
				
					<!-- 路线信息 -->
					<view class="from-and-to">
						<view class="from">
							<view class="dot green"></view>
							<view class="text">起点：{{ order.currentAddr }}</view>
						</view>
						<view class="to">
							<view class="dot red"></view>
							<view class="text">终点：{{ order.targetAddr }}</view>
						</view>
					</view>
				
					<!-- 时间信息 -->
					<view class="time-info" v-if="order.status === orderTypeEnum.GET.code">
						<view class="time-item">
							<text class="label">出发时间：</text>
							<text class="value">{{ formatHopeTime(order.hopeTime) }}</text>
						</view>
					</view>
				
					<!-- 预计收入 和 操作按钮 -->
					<view class="footer">
						<!-- 收益信息 -->
						<view class="profit">
							<text class="actual" v-if="order.status === orderTypeEnum.FINISH.code">
								实收：¥{{ formatAmount(order.price) }}
							</text>
							<text class="expected" v-else-if="order.status === orderTypeEnum.REFUNDED.code">
								已退款：¥{{ formatAmount(order.price) }}
							</text>
							<text class="expected" v-else>
								预计：¥{{ formatAmount(order.price) }}
							</text>
						</view>
						
						<!-- 操作按钮 -->
						<view class="actions" v-if="[orderTypeEnum.GET.code, orderTypeEnum.WAITING.code, orderTypeEnum.START.code].includes(order.status)">
							<!-- <view
								class="btn cancel" 
								v-if="[orderTypeEnum.GET.code, orderTypeEnum.WAITING.code].includes(order.status)"
								@click="handleAction(order.id, '取消订单', orderTypeEnum.CANCEL.code)"
							>
								取消订单
							</view> -->
							<view
								class="btn primary-btn"
								v-if="[orderTypeEnum.GET.code, orderTypeEnum.WAITING.code, orderTypeEnum.START.code].includes(order.status)"
								@click="handleAction(order.id, status2text(order.status), order.status + 1)" 
							>
								{{ status2text(order.status) }}
							</view>
						</view>
					</view>
					
				</view>
			</Page>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { formatDatetime } from '@/utils/datetimeUtil.js'
import { orderTypeEnum, getTypeNameByCode } from '@/utils/orderType.js'
import { getAllMyOrderList, updateStatus, cancelOrder, finishOrder } from '@/api/order.js'
import { onPullDownRefresh, onShow, onReachBottom } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/userStore.js'
import { formatAmount } from '@/utils/amountUtil.js'
import { getUserAvatarOrDefault } from '@/utils/imageUtil.js'
import Page from '@/components/page.vue'
// #ifdef APP-PLUS
import recorderManager from "@/utils/recorderManager"
// #endif

const driver = useUserStore()

/** 状态栏高度 */
const statusBarHeight = uni.getSystemInfoSync().statusBarHeight

// 订单数据
const orderList = ref([
	/* {
	    id: null,
	    businessType: null,
	    currentLo: null,
	    currentLa: null,
	    currentAddr: null,
	    targetLo: null,
	    targetLa: null,
	    targetAddr: null,
	    orderTime: null,
	    hopeTime: null,
	    receiveTime: null,
	    reachTime: null,
	    startTime: null,
	    endTime: null,
		finishTime: null,
	    price: 0,
	    userId: null,
		username: null,
		avatar: null,
	    userPhone: null,
	    driverId: 0,
	    status: 0,
	    remark: null,
	    
	} */
])

const pageRef = ref(null)
const page = reactive({
	pageNum: 1,
	pageSize: 10,
	status: null
})

// 筛选选项
const filterOptions = []
filterOptions.unshift({ code: 0, msg: '全部订单' })
Object.keys(orderTypeEnum).forEach(k => {
	if (k !== 'WAIT') {
		filterOptions.push(orderTypeEnum[k])
	}
})

const currentFilter = ref(0)

// 当司机创单时没有出发时间，显示当前时间
function formatHopeTime(time) {
	if (!time) {
		// 如果没有出发时间，显示当前时间
		return formatDatetime(new Date())
	}
	return formatDatetime(time)
}

// 根据状态返回文字
function status2text (status) {
	switch (status) {
		case orderTypeEnum.GET.code:
			return '开始等待'
		case orderTypeEnum.WAITING.code:
			return '开始服务'
		case orderTypeEnum.START.code:
			return '完成订单'
	}
}

// 处理订单操作
function handleAction (id, action, status) {
	uni.showModal({
		title: '提示',
		content: `确定要${action}吗？`,
		success: (res) => {
			if (res.confirm) {
				if (status === orderTypeEnum.CANCEL.code) {
					// 取消订单
					cancelOrder(id).then(() => {
						const od = orderList.value.find(v => v.id === id)
						od.status = status
						uni.showToast({
							title: '操作成功',
							icon: 'none'
						})
					})
				} else {
					// 等待 或 开始 或 完成 订单
					const od = orderList.value.find(v => v.id === id)
					if (status === orderTypeEnum.PENDING_PAY.code) {
						// 如果是司机点击“完成订单”，那么传过来这个status就是待支付，需要司机选择用户的支付方式
						uni.showActionSheet({
							title: '请选择用户的支付方式',
							itemList: ['小程序线上支付', '扫码支付', '现金支付'],
							success: function (res) {
								if (res.tapIndex === 0) {
									// 线上支付:
									// 需要司机更新订单状态为待支付。                  ⭐需要执行的操作
									// 直接在司机账户里扣钱(即平台抽成和上线提成)。     ⭐需要执行的操作
									// 等到用户支付后，把全部钱加回到司机的账户余额中。
									finishOrder({ orderId: id, payType: 0 }).then(res => {
										od.status = orderTypeEnum.PENDING_PAY.code
										uni.showToast({
											title: '操作成功',
											icon: 'none'
										})
									})
								} else {
									// 线下支付:
									// 需要司机更新订单状态为已完成。                  ⭐需要执行的操作
									// 直接在司机账户里扣钱(即平台抽成和上线提成)。     ⭐需要执行的操作
									finishOrder({ orderId: id, payType: res.tapIndex }).then(res => {
										od.status = orderTypeEnum.FINISH.code
										uni.showToast({
											title: '操作成功',
											icon: 'none'
										})
									})
								}
							},
							fail: function (res) {
								console.log(res.errMsg);
							}
						});
					} else {
						// 其他操作，直接更新状态即可
						updateStatus({ id, status }).then(() => {
							od.status = status
							uni.showToast({
								title: '操作成功',
								icon: 'none'
							})
						})
					}
					
					// 录音
					// #ifdef APP-PLUS
					if (orderTypeEnum.START.code === status) {
						recorderManager.setCurrentOrderId(id)
						recorderManager.startRecord()
					} else if (orderTypeEnum.PENDING_PAY.code === status) {
						recorderManager.endRecord()
					}
					// #endif
				}
				
			}
		}
	})
}

// 筛选变更
function filterChange (e) {
	currentFilter.value = filterOptions[e.detail.value].code
	
	page.status = currentFilter.value === 0 ? null : currentFilter.value
	pageRef.value.resetPage()
}

// 跳转到详情页
function gotoInfoPage (order) {
	// #ifdef APP-PLUS
	uni.navigateTo({
		url: `/pages/index/info?query=${JSON.stringify(order)}`
	})
	// #endif
	// #ifndef APP-PLUS
	uni.navigateTo({
		url: `/pages/index/info2?query=${JSON.stringify(order)}`
	})
	// #endif
}

onPullDownRefresh(() => {
	pageRef.value.resetPage()
	uni.stopPullDownRefresh()
	uni.showToast({
		icon: 'none',
		title: '刷新成功'
	})
})

// onShow(() => {
//     console.log('=== 订单页面调试信息 ===')
// 	console.log('当前司机Id:', driver.getCurrentDriver().id)
//     console.log('当前筛选状态:', currentFilter.value)
//     console.log('订单列表数据:', orderList.value)
//     console.log('当前页码:', page.pageNum)
//     console.log('页面大小:', page.pageSize)
//     console.log('筛选状态:', page.status)
//     console.log('========================')
// })
</script>

<style lang="scss">
$secondary-color: #f8f9fa;
$text-color: #333;
$light-text: #666;
$border-color: #eaeaea;

// #ifdef APP-PLUS
$header-height: 165rpx;
// #endif

// #ifndef APP-PLUS
$header-height: 120rpx;
// #endif

view {
	box-sizing: border-box;
}

.order-page {
	min-height: 100vh;
	background-color: $secondary-color;

	.header {
		position: fixed;
		top: 0;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		
		height: $header-height;
		background-color: #fff;
		z-index: 10;
		padding: 0 30rpx;
		border-bottom: 1rpx solid #ccc;

		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: $text-color;
		}

		.filter {
			.filter-btn {
				padding: 8rpx 20rpx;
				background-color: white;
				border-radius: 30rpx;
				border: 1rpx solid $border-color;
				font-size: 26rpx;
				color: $light-text;
				display: flex;
				align-items: center;
			}
		}
	}
	.fill {
		width: 100%;
		height: $header-height;
	}

	.order-list {
		width: 100%;
		min-height: calc(100vh - $header-height);

		.empty {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 70vh;

			image {
				width: 500rpx;
				height: 500rpx;
				margin-bottom: 30rpx;
				opacity: 0.6;
			}

			text {
				color: $light-text;
				font-size: 28rpx;
			}
		}

		.order-card {
			background-color: white;
			border-radius: 16rpx;
			padding: 24rpx;
			margin-top: 24rpx;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
			overflow: hidden;
			
			.user-info {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					margin-right: 16rpx;
				}

				.username {
					font-size: 30rpx;
					font-weight: bold;
					color: $text-color;
					width: 250rpx;
					flex-wrap: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
				}

				.tag-container {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: flex-end;
					&>view {
						padding: 6rpx 16rpx;
						border-radius: 20rpx;
						font-size: 24rpx;
						margin-left: 20rpx;
					}
					.view-more {
						background-color: rgba($light-text, 0.1);
						color: $light-text;
					}
					.status-tag {
						background-color: rgba($uni-color-primary, 0.1);
						color: $uni-color-primary;
					}
				}
			}

			.from-and-to {
				&>view {
					margin-bottom: 20rpx;
					font-size: 28rpx;
					display: flex;
					align-items: center;
					justify-content: flex-start;
					.dot {
						width: 18rpx;
						height: 18rpx;
						border-radius: 50%;
						margin-right: 15rpx;
					}
					.green {
						background-color: #00b400;
					}
					.red {
						background-color: #d60000;
					}
					.text {
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						width: 600rpx;
					}
				}
				.from {
				}
				.to {
				}
			}

			.time-info {
				margin-bottom: 20rpx;

				.time-item {
					display: flex;
					margin-bottom: 8rpx;
					font-size: 26rpx;

					.label {
						color: $light-text;
						margin-right: 10rpx;
					}

					.value {
						color: $text-color;
					}
				}
			}

			.footer {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 20rpx;
				border-top: 1rpx solid $border-color;
				// 收益
				.profit {
					font-size: 28rpx;
					padding-top: 24rpx;
					.expected {
						color: #d9001b;
						font-weight: bold;
					}
					.actual {
						color: $uni-color-primary;
						font-weight: bold;
					}
				}
				// 操作按钮
				.actions {
					display: flex;
					justify-content: flex-end;
					margin-top: 24rpx;
				
					.btn {
						margin-left: 30rpx;
						padding: 0 24rpx;
						height: 60rpx;
						line-height: 60rpx;
						font-size: 26rpx;
						border-radius: 15rpx;
						color: #fff;
						border: none;
				
						&.cancel {
							background-color: #d33215;
						}
					}
				}
			}
		}

		// 加载更多
		.loading-container {
			width: 100%;
			text-align: center;
			// padding: 20rpx;
			font-size: 22rpx;
		}
	}
}
</style>